package com.hippo.provider.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hippo.core.pojo.vo.result.BaseResult;
import com.hippo.provider.config.WechatConfig;
import com.hippo.provider.service.WechatLoginService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;


/**
 * @ClassName WechatLoginServiceImpl
 * @Description TODO 微信登录业务处理
 * @Author tangxl
 * @create 2023-04-03 18:56
 **/
@Service
public class WechatLoginServiceImpl implements WechatLoginService {
    @Resource
    private WechatConfig wechatConfig;
    /**
     * 获取OpenId接口
     * @return
     */
    @Override
    public BaseResult getOpenId(String code) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", wechatConfig.getAppId());
        paramMap.put("secret", wechatConfig.getAppSecret());
        paramMap.put("js_code", code);
        // 调用微信接口获取OpenId
        String result= HttpUtil.get(wechatConfig.getOpenIdUrl(), paramMap);
        System.out.println("获取OpenId返回结果："+result);
        JSONObject entries = JSONUtil.parseObj(result);
        String openId = entries.getStr("openid");
        System.out.println(result);
        if(StringUtils.isEmpty(openId)){
            return BaseResult.fail(entries.getStr("errmsg"));
        }
        return BaseResult.ok(openId);
    }
}
